<template>
  <div class="page-coupon">
    <!-- 新版规范 -->
    <div class="coupon-mod">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form
          ref="test-form"
          :inline="true"
          class="search-form"
          :model="searchForm"
          label-width="auto"
          @submit.prevent
        >
          <div class="input-row">
            <el-form-item :label="$t('coupon.couponName') + ':'">
              <el-input
                v-model="searchForm.couponName"
                :placeholder="$t('coupon.couponName')"
              />
            </el-form-item>
            <el-form-item :label="$t('coupon.expStatus') + ':'">
              <el-select
                v-model="searchForm.overdueStatus"
                :placeholder="$t('coupon.expStatus')"
              >
                <el-option
                  v-for="item in overdueOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('coupon.launchStatus') + ':'">
              <el-select
                v-model="searchForm.putonStatus"
                :placeholder="$t('coupon.launchStatus')"
              >
                <el-option
                  v-for="item in putonOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <!-- 日期组件 -->
            <el-form-item :label="$t('coupon.expire') + ':'">
              <el-date-picker
                v-model="dateRange"
                type="datetimerange"
                :range-separator="$t('date.tip')"
                value-format="YYYY-MM-DD HH:mm:ss"
                :start-placeholder="$t('date.start')"
                :end-placeholder="$t('date.end')"
                :default-time="defaultTime"
              />
            </el-form-item>
            <el-form-item>
              <div
                class="default-btn primary-btn"
                @click="onSearch(true)"
              >
                {{ $t('station.search') }}
              </div>
              <div
                class="default-btn"
                @click="onClearSearch"
              >
                {{ $t('temp.setNull') }}
              </div>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <!-- 搜索栏end -->
      <!-- 表格主体 -->
      <div class="main-container">
        <div class="operation-bar">
          <div
            v-if="isAuth('admin:coupon:save')"
            class="default-btn primary-btn"
            @click="onAddOrUpdate()"
          >
            {{ $t('crud.addTitle') }}
          </div>
        </div>
        <!-- 表格 -->
        <div class="table-con seckill-table">
          <el-table
            :data="dataList"
            header-cell-class-name="table-header"
            row-class-name="table-row-low"
            stripe
            style="width: 100%"
          >
            <el-table-column
              align="left"
              prop="couponName"
              :label="$t('coupon.couponName')"
            >
              <template #default="scope">
                <span class="table-cell-text">{{ scope.row.couponName }}</span>
              </template>
            </el-table-column>

            <el-table-column
              align="left"
              prop="couponType"
              :label="$t('coupon.couponType')"
            >
              <template #default="scope">
                <div class="tag-text">
                  {{
                    ['', $t('coupon.voucher'), $t('coupon.discountCoupon'), $t('coupon.excCerti')][
                      scope.row.couponType
                    ]
                  }}
                </div>
              </template>
            </el-table-column>

            <el-table-column
              width="150"
              align="left"
              prop="startTime"
              :label="$t('coupon.startTime')"
            >
              <template #default="scope">
                <span class="table-cell-text">{{ scope.row.startTime || '-' }}</span>
              </template>
            </el-table-column>

            <el-table-column
              width="150"
              align="left"
              prop="endTime"
              :label="$t('coupon.endTime')"
            >
              <template #default="scope">
                <span class="table-cell-text">{{ scope.row.endTime || '-' }}</span>
              </template>
            </el-table-column>

            <el-table-column
              align="center"
              prop="overdueStatus"
              :label="$t('coupon.expStatus')"
            >
              <template #default="scope">
                <div class="tag-text">
                  {{ [$t('coupon.exp'), $t('coupon.notExp')][scope.row.overdueStatus] }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="putonStatus"
              :label="$t('coupon.launchStatus')"
            >
              <template #default="scope">
                <div
                  v-if="scope.row.putonStatus !== -1"
                  class="tag-text"
                >
                  {{
                    [$t('coupon.waitAutoLaunch'), $t('coupon.launched'), $t('coupon.waitLaunch')][
                      scope.row.putonStatus
                    ]
                  }}
                </div>
                <div
                  v-else
                  class="tag-text"
                >
                  {{ $t('coupon.cancelLaunch') }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="launchTime"
              :label="$t('coupon.timeToMarket')"
            >
              <template #default="scope">
                <span class="table-cell-text">{{ scope.row.launchTime || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="stocks"
              :label="$t('coupon.stock')"
              sortable
            />
            <el-table-column
              align="center"
              :label="$t('crud.menu')"
              class=""
            >
              <template #default="scope">
                <div class="text-btn-con">
                  <div
                    v-if="isAuth('admin:coupon:update')"
                    class="default-btn text-btn"
                    @click="onAddOrUpdate(scope.row.couponId)"
                  >
                    {{ scope.row.overdueStatus === 0 ? $t('crud.viewTitle') : $t('temp.modify') }}
                  </div>
                  <div
                    v-if="isAuth('admin:coupon:auditApply') && scope.row.putonStatus > 1"
                    class="default-btn text-btn"
                    @click="auditEventHandle(scope.row.couponId)"
                  >
                    {{
                      scope.row.putonStatus === 2
                        ? $t('coupon.applyForListing')
                        : $t('coupon.waitReview')
                    }}
                  </div>
                  <div
                    v-if="isAuth('admin:coupon:delete')"
                    class="default-btn text-btn"
                    @click="onDelete(scope.row.couponId)"
                  >
                    {{ $t('text.delBtn') }}
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 分页 -->
        <el-pagination
          v-if="dataList.length"
          :current-page="page.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
          @update:page-size="onPageSizeChange"
          @update:current-page="onPageChange"
        />
      </div>
      <!-- 表格主体end -->
    </div>

    <!-- 弹窗, 新增 / 修改 -->
    <AddOrUpdate
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      add-or-update
      @refresh-data-list="refreshChange"
    />
  </div>
</template>

<script setup>
import AddOrUpdate from './add-or-update.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { isAuth } from '@/utils/index'

let tempSearchForm = null // 保存上次点击查询的请求条件

const dateRange = ref([])
const defaultTime = ref([
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59)
])
const overdueOptions = [
  {
    value: 0,
    label: $t('coupon.exp')
  },
  {
    value: 1,
    label: $t('coupon.notExp')
  }
]
const putonOptions = [
  {
    value: -1,
    label: $t('coupon.cancelLaunch')
  },
  {
    value: 0,
    label: $t('coupon.waitAutoLaunch')
  },
  {
    value: 1,
    label: $t('coupon.launched')
  },
  {
    value: 2,
    label: $t('coupon.waitLaunch')
  }
]
const dataList = ref([])

const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
// 头部搜索表单
const searchForm = reactive({
  couponName: null,
  overdueStatus: null,
  putonStatus: null
})

onMounted(() => {
  getDataList()
})

// 获取数据列表
const getDataList = (pageParam, newData = false) => {
  if (newData || !tempSearchForm) {
    const temp = JSON.parse(JSON.stringify(searchForm))
    tempSearchForm = {
      ...temp,
      startTime: dateRange.value === null ? null : dateRange.value[0], // 开始时间
      endTime: dateRange.value === null ? null : dateRange.value[1] // 结束时间
    }
  }
  http({
    url: http.adornUrl('/admin/coupon/page'),
    method: 'get',
    params: http.adornParams(Object.assign(tempSearchForm, {
      current: pageParam == null ? page.currentPage : pageParam.currentPage,
      size: pageParam == null ? page.pageSize : pageParam.pageSize
    }), false)
  }).then(({ data }) => {
    dataList.value = data.records
    page.total = data.total
    page.currentPage = data.current
  })
}

// 新增 / 修改
const addOrUpdateRef = ref(null)
const addOrUpdateVisible = ref(false)
const onAddOrUpdate = val => {
  addOrUpdateVisible.value = true
  nextTick(() => {
    addOrUpdateRef.value?.init(val)
  })
}

// 删除
const onDelete = id => {
  const ids = [id]
  ElMessageBox.confirm(
    `${$t('sys.makeSure')}${id ? $t('text.delBtn') : $t('sys.batchDelete')}${$t('text.menu')}?`,
    $t('text.tips'),
    {
      confirmButtonText: $t('crud.filter.submitBtn'),
      cancelButtonText: $t('crud.filter.cancelBtn'),
      type: 'warning'
    }
  ).then(() => {
    http({
      url: http.adornUrl('/admin/coupon'),
      method: 'delete',
      data: http.adornData(id, false)
    }).then(() => {
      page.total = page.total - ids.length
      ElMessage({
        message: $t('publics.operation'),
        type: 'success',
        duration: 1500,
        onClose: () => {
          refreshChange()
        }
      })
    })
  })
}
// 条件查询
const onSearch = (newData = false) => {
  page.currentPage = 1
  getDataList(page, newData)
}
// 刷新回调用
const refreshChange = () => {
  addOrUpdateVisible.value = false
  getDataList(page)
}
// 每页数量变更
const onPageSizeChange = val => {
  page.pageSize = val
  getDataList()
}
// 页数变更
const onPageChange = val => {
  page.currentPage = val
  getDataList()
}
const onClearSearch = () => {
  dateRange.value = []
  searchForm.couponName = null
  searchForm.overdueStatus = null
  searchForm.putonStatus = null
}
</script>
